package com.fnst.facedetect.compare;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class FaceContrast {

	protected Logger log = LoggerFactory.getLogger(getClass());
	
	private static String userName = "admin";
	private static String password = "softwise";
	

	public String imgContrast(String idCard, String fileStr1, String fileStr2) throws Exception{
		String result = null;
		BaseResultBean score = null;
		try {
			// webservice的心跳url
			//String heartCheckUrl = "/verify_info/heart_req";
			
			// webservice的对比url
			String verifyUrl = "/verify_info/score";
			
			// webservice的繁忙url
			//String busyUrl = "/verify_info/busy_req";

			String strUrl = "http://10.101.162.1:8082";
			// 发送心跳请求
			//BaseResultBean heartCheckResult = JsonHelper.json2Object(get(strUrl + heartCheckUrl), BaseResultBean.class);
			// 发送繁忙请求
			//BaseResultBean busyCheckResult = JsonHelper.json2Object(get(strUrl + busyUrl), BaseResultBean.class);

			String urlStr = strUrl + verifyUrl;
			Map<String, String> textMap = new HashMap<String, String>();
			textMap.put("name", "");
			textMap.put("id_card", idCard);
			textMap.put("gender", "");
			textMap.put("birthdate", "");
			textMap.put("user_id", "");
			textMap.put("terminal_id", "");

			Map<String, String> fileMap = new HashMap<String, String>();

			fileMap.put("live_image_stream", fileStr1);
			fileMap.put("certificate_image_stream", fileStr2);

			score = JsonHelper.json2Object(post(urlStr, textMap, fileMap), BaseResultBean.class);
			
			if(score == null){
				log.warn("score null");
				result = "拍照图片未发现人脸";
			}
			
			log.info("=== score ===");
			log.info("idCard: " + idCard);
			log.info("score: " + score.score);
			log.info("error_code: " + score.error_code);
			log.info("message: " + score.message);

			/*System.out.println("心跳检测:" + heartCheckResult.return_code);
			System.out.println("繁忙检测:" + busyCheckResult.return_code);
			System.out.println("对比结果:" + score.score);
			System.out.println("message:" + score.message);
			System.out.println("error_code:" + score.error_code);*/
		} finally {
		}
		if (score != null && score.error_code == null) {
			result = score.score;
		} else {
			if ("err_016".equals(score.error_code) || "err_018".equals(score.error_code)) {
				result = score.message.replaceAll("捕获", "拍照");
			} else if ("err_017".equals(score.error_code) || "err_019".equals(score.error_code)) {
				result = score.message.replaceAll("身份证", "样本");
			} else if ("err_020".equals(score.error_code)) {
				result = score.message.replaceAll("两张", "拍照和样本");
			} else {
				result = "拍照图片未发现人脸";
			}
		}
		return result;
	}

	private String post(String urlStr, Map<String, String> textMap,
			Map<String, String> fileMap) throws Exception {
		String res = "";
		HttpURLConnection connection = null;
		String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
		try {
			URL url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(30000);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			String encoding = new String(Base64.encode(new String(userName
					+ ":" + password).getBytes()));
			// 设置用户名和密码
			connection.setRequestProperty("Authorization", "Basic " + encoding);
			connection.setRequestProperty("accept", "application/json");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);

			OutputStream out = new DataOutputStream(connection.getOutputStream());
			// text
			if (textMap != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = textMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append(
							"\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""
							+ inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}

			// file
			if (fileMap != null) {
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					String filename = inputName + ".jpg";
					String contentType = "application/octet-stream";

					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append(
							"\r\n");
					strBuf.append("Content-Disposition: form-data; name=\""
							+ inputName + "\"; filename=\"" + filename
							+ "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
					out.write(strBuf.toString().getBytes());
					out.write(Base64.decode(inputValue));
				}
			}

			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();

			// 读取返回数据
			StringBuffer strBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			res = strBuf.toString();
			reader.close();
			reader = null;
		} catch (Exception e) {
//			res = "{\"error_code\":\"err_018\",\"message\":\"捕获图片未发现人脸\"}";
//			System.out.println("发送POST请求出错。" + urlStr);
//			e.printStackTrace();
			throw new Exception("照片对比服务出错");
		} finally {
			if (connection != null) {
				connection.disconnect();
				connection = null;
			}
		}
		return res;
	}

	protected String get(String url) throws IOException {
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();

			connection.setRequestProperty("accept", "application/json");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			String encoding = new String(Base64.encode(new String(userName
					+ ":" + password).getBytes()));
			// 设置用户名和密码
			connection.setRequestProperty("Authorization", "Basic " + encoding);

			// 设置超时时间
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(5000);
			// 建立实际的连接
			//connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return result;
	}
}
